package framework.threads
{
    import flash.utils.Dictionary;

    import framework.ArtificialToken;
    import framework.Utils;

    import mx.rpc.AsyncToken;

    public class Thread
    {
        public var runnable:IRunnable;

        public var token:AsyncToken;

        static public var threads:Dictionary = new Dictionary();

        public function Thread(runnable:IRunnable)
        {
            this.runnable = runnable;
        }

        public function start():AsyncToken
        {
            token = new ArtificialToken(null);
            Utils.callLater(executeNextStep);
            threads[runnable] = this;
            return token;
        }

        private function executeNextStep():void
        {
            var stopped:Boolean = runnable.nextStep();
            if (stopped)
            {
                delete threads[runnable];
                ArtificialToken(token).resultHandlerForResult(null);
            }
            else
            {
                Utils.callLater(executeNextStep);
            }
        }

    }
}